#include "time1c1.h"
// #include <stdbool.h> // 如果编译器不支持，可以不用

#define true 1
#define false 0
typedef unsigned char bool;

DPOOL_txDIF_tstClkDpoolData DPOOL_txDIF_stClkDpoolData = {0,0,0};

/*time init function */
void time_vInit(void)
{
   
}
/*time main function */
void time_vMain(void)
{
    // 1. 读取输入信号
    uint16 canHour = TimeSet_Hour_ReadSval;
    uint16 canMin = TimeSet_Minutes_ReadSval;
    uint16 canMode = TimeMod_ReadSval;
    bool hourTimeout = Flg_TimeSet_Hour_fv;
    bool minTimeout = Flg_TimeSet_Minutes_fv;
    bool modeTimeout = Flg_TimeMod_fv;

    static uint16 localHour = 0;
    static uint16 localMin = 0;
    static uint16 localMode = 0; // 0:24h, 1:12h
    static uint16 lostSignalCnt = 0;
    const uint16 TIMEOUT_CYCLE = 10;
    static bool useLocalClock = false;

    // 2. 信号超时计数
    if (hourTimeout || minTimeout) {
        if (lostSignalCnt < TIMEOUT_CYCLE) lostSignalCnt++;
    } else {
        lostSignalCnt = 0;
    }
    // 3. 判断是否用本地时钟
    if (lostSignalCnt >= TIMEOUT_CYCLE) {
        useLocalClock = true;
    } else {
        useLocalClock = false;
    }

    // 4. CAN信号有效，且时分合法，立即刷新显示
    if (!useLocalClock && canHour <= 23 && canMin <= 59) {
        DPOOL_txDIF_stClkDpoolData.DIF_u16Hour = canHour;
        DPOOL_txDIF_stClkDpoolData.DIF_u16Min = canMin;
        DPOOL_txDIF_stClkDpoolData.DIF_u16Mode = canMode;
        localHour = canHour;
        localMin = canMin;
        localMode = canMode;
    } else if (useLocalClock) {
        // 5. 超时后用本地时钟自增
        localMin++;
        if (localMin >= 60) {
            localMin = 0;
            localHour++;
            if (localMode == 0) { // 24小时制
                if (localHour >= 24) localHour = 0;
            } else { // 12小时制
                if (localHour >= 12) localHour = 0;
            }
        }
        DPOOL_txDIF_stClkDpoolData.DIF_u16Hour = localHour;
        DPOOL_txDIF_stClkDpoolData.DIF_u16Min = localMin;
        DPOOL_txDIF_stClkDpoolData.DIF_u16Mode = localMode;
    }
    // 6. 断电后默认24小时制00:00（假设有外部调用init时重置）
    // 这里不做特殊处理，默认全局变量已初始化为0
}
